<?php
namespace app\home\Controller;
use think\Controller;
use think\captcha;
use think\Validate;

class Index extends Controller
{
    protected $admin;
    protected $user;
    public function __construct()
    {
        parent::__construct();
        $this->admin = model('Admin');
        $this->user = model('User');
    }

    //登录入口
    public function index()
    {
        if((session('?aid') && session('?username'))||(cookie('aid')&&cookie('username'))){
            if(cookie('aid')&&cookie('username')){
                session('aid',cookie('aid'));
                session('username',cookie('username'));
            }
            return $this->redirect('main/index');
        }
        return $this->fetch();

    }
    //登录
    public function login()
    {
        $data = input('post.');
        $captcha = new captcha\Captcha();
        if (!$captcha->check($data['verify'])) {
            $ajaxresult = ['rel'=>0,'msg'=>'验证码错误'];
            return json($ajaxresult);
        }

        // 数据验证
        $validate = new Validate(['name'=>'require','pwd'=>'require'],['name'=>'用户名必须填写','name.max'=>'密码必须填写']);
        if (!$validate->check($data)) {
            $ajaxresult = array('rel'=>0,'msg'=>$validate->getError());
            return json($ajaxresult);
        }else{
            $where = ['name'=>$data['name']];
            $userinfo = $this->admin->where($where)->find();

            if(!empty($userinfo)){
                $pwd = md5($data['pwd']);
                if($userinfo['pwd']==$pwd){
                    $logintime = $this->admin->where(["id"=>$userinfo['id']])->update(["update_time"=>time()]);
                    if (!$logintime){
                        $ajaxresult = ['rel'=>0,'msg'=>'登录失败'];
                        return json($ajaxresult);
                    }
                    session('username',$data['name']);
                    session('aid',$userinfo['id']);
                    session('roleid',$userinfo['roleid']);
                    if($data['remme']=='1'){
                        cookie('username',$data['name'],3600*24*7);
                        cookie('aid',$userinfo['id'],3600*24*7);
                        cookie('roleid',$userinfo['roleid'],3600*24*7);
                    }
                    $ajaxresult = ['rel'=>1,'msg'=>'登录成功'];
                    return json($ajaxresult);
                }else{
                    $ajaxresult = array('rel'=>0,'msg'=>'用户名或密码错误');
                    return json($ajaxresult);
                }
            }else{
                $ajaxresult = ['rel'=>0,'msg'=>'用户名或密码错误'];
                return json($ajaxresult);
            }
        }
    }

    //提示信息
    public static function msg($msg,$url=""){
        header("Content-type:text/html;charset=utf-8");
        echo "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><script src='/static/common/jquery.min.js'/></script>
    		 <script src='/static/common/layer/layer.js'/></script>
    		 <script>$(function(){layer.alert('$msg',function(index){location.href='$url';layer.close(index);
				});})</script></head><body></body></html>";
    }

    //退出
    public function loginOut(){
        cookie(null,'du_');
        session(null);
        $ajaxresult = ['rel'=>1,'msg'=>'退出成功'];
        return json($ajaxresult);
    }

    public function sendMailByDate($section=1)
    {
        $now=time();
        $ymd=date('Y-m-d');
        $nyr=date('Y年m月d日');
        //根据部门获得两个用户，获得今天的是否工作日
        $user_list=$this->user->alias('a')->where(array('section'=>intval($section)))->limit(1)->join('_Section_ s','a.section = s.id')->field('a.id,a.name,a.email,s.name as section_name,s.is_copy,s.copy_name,s.send_name,s.area,a.section,a.update_time')->order(array('a.work_date'=>'asc'))->select();

        //$user_list=model('user')->where(array('section'=>'1'))->limit(1) ->order(array('work_date'=>'asc'))->select();
        $output=$this->get_work_day($now);
        if($output==0){
            foreach ($user_list as $v){
                $subject=$v['name'].'在'.$nyr.'的值日通知';
                $content = '<h3>'.$v['name']."的值日邮件通知</h3><table>
                            <tr><td>值日人员：</td><td>".$v['name']."</td></tr>";
                $content .="<tr><td>内容：</td><td>此邮件为值日通知邮件，请于收到邮件后进行卫生值日工作！</td></tr>
                            <tr><td>清洁区域：</td><td>".$v['area']."</td></tr>
                            <tr><td>时间</td><td>".$ymd."</td></tr>";
                if ($v['is_copy']==1&&!empty($v['copy_name'])){
                    $content .="<tr><td>抄送人：</td><td>" . $v['send_name'] . "</td></tr>
                                <tr><td>抄送人邮箱</td><td>".$v['copy_name']."</td></tr>";
                }
                $content .= "</table><h5>完成后请与上级确认</h5>";

                //发送邮件
                $res=sendMail($v['email'],$subject,$content,$v['name']);
                if ($res['rel']==0){
                    return $res['msg'];
                }
                //保存邮件发送时间
                $res=$this->user->where(['id'=>$v['id']])->update(['work_date'=>$now]);
                if($res){
                    if($v['is_copy']==1&&!empty($v['copy_name'])){
                        $subject2=$v['name'].'在'.$nyr.'的值日抄送通知';
                        $content2 = '<h3>'.$v['name']."的值日邮件抄送通知</h3><table>
                                    <tr><td>值日人员：</td><td>".$v['name']."</td></tr>";
                        $content2 .="<tr><td>内容：</td><td>此邮件为抄送邮件！</td></tr>
                                    <tr><td>清洁区域：</td><td>".$v['area']."</td></tr>
                                    <tr><td>时间</td><td>".$ymd."</td></tr>";
                        $content2 .= "</table>";
                        $copy_result=sendMail($v['copy_name'],$subject2,$content2,$v['send_name']);
                        return json($copy_result);
                    }else{
                        $copy_result=['rel'=>0,'msg'=>'抄送人不存在'];
                        return json($copy_result);
                    }
                }else{
                    return "向{$v['name']}发送邮件失败<br/>";
                }
            }
        }else{
            return "发送邮件失败";
        }
    }

    private function get_work_day($time){
        $date=date('Ymd',$time);
        $url='http://tool.bitefu.net/jiari/?d='.$date;
        //初始化
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        return $output;
    }

}
